//
//  NHPlayerView.m
//  17  视频播放器
//
//  Created by dllo on 16/2/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NHPlayerView.h"
#import <AVFoundation/AVFoundation.h>

#define Width self.frame.size.width
#define Height self.frame.size.height

@interface NHPlayerView ()

// 播放器
@property(nonatomic, retain)AVPlayer *player;
// 视频项目对象
@property(nonatomic, retain)AVPlayerItem *playerItem;
// 播放器的承载对象
@property(nonatomic, retain)AVPlayerLayer *playerLayer;

// 视频播放结束的时候显示的视图
@property(nonatomic, retain)UIView *playEndView;

// 显示进度时间的Label
@property(nonatomic, retain)UILabel *timeLabel;
// 显示总时间的Label
@property(nonatomic, retain)UILabel *durationTimeLabel;
// 显示进度的进度条
@property(nonatomic, retain)UISlider *progressSlider;
// 底部进度显示视图
@property(nonatomic, retain)UIView *bottomView;
// 显示播放按钮
@property(nonatomic, retain)UIImageView *playButtonImageView;
// 保存视频的总时长
@property(nonatomic, assign)CGFloat durationTime;
// 判断是否点击了播放视图
@property(nonatomic, assign)BOOL isTap;
// 判断当前视频是否开始播放了
@property(nonatomic, assign)NSInteger isPlay;
// 加载视频时候出现的加载图标
@property(nonatomic, retain)UIActivityIndicatorView *indicator;

@end

@implementation NHPlayerView

// 初始化方法
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        
        // 创建视频结束的时候显示的视图
        [self createPlayEndView];
    }
    return self;
}

#pragma mark 设置PlayerURLStr
- (void)setPlayerURLStr:(NSString *)playerURLStr{
    if(_playerURLStr != playerURLStr){
        _playerURLStr = playerURLStr;
    }
    // 创建播放器
    [self createPlayerView];
    // 启动播放器
    [self playerPlay];
}

#pragma mark 创建播放视图
- (void)createPlayerView{
    
    // 对播放网址进行编码
    _playerURLStr = [self.playerURLStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *playerURL = [NSURL fileURLWithPath:self.playerURLStr];//[NSURL URLWithString:self.playerURLStr];
    // 创建视频项目对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:playerURL];
    // 创建播放器对象
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    // 创建播放器承载对象
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    // 设置承载对象尺寸
    self.playerLayer.frame = CGRectMake(5, 5, Width - 10, Height - 10);
    // 设置填充方式为填满
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    // 添加播放器
    [self.layer insertSublayer:self.playerLayer atIndex:0];
    
    // 创建播放按钮
    self.playButtonImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.playButtonImageView.center = CGPointMake(Width / 2, Height / 2);
    [self.playButtonImageView setImage:[UIImage imageNamed:@"PlayIcon_64_01"]];
    self.playButtonImageView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.playButtonImageView];
    // 隐藏
    [self.playButtonImageView setHidden:YES];
    
    // 创建底部的进度显示视图
    [self createBottomView];
    
    // 创建轻点手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPlayerView:)];
    [self addGestureRecognizer:tap];
    self.isTap = NO;
    
    // 添加监听方式
    [self addNotificationCenters];
    
    // 设置播放进度
    [self addPlayProgress];
    
}
#pragma mark 创建底部的进度显示视图
- (void)createBottomView{
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, Height - 25, Width, 20)];
    self.bottomView.backgroundColor = [UIColor colorWithRed:246 / 255.0 green:246 / 255.0 blue:246 / 255.0 alpha:1];
    self.bottomView.alpha = 0;
    [self addSubview:self.bottomView];
    
    // 进度时间Label
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 3, 40, 15)];
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    self.timeLabel.text = @"00:00";
    [self.bottomView addSubview:self.timeLabel];
    // 总时间
    self.durationTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(Width - 50, 3, 40, 15)];
    self.durationTimeLabel.font = [UIFont systemFontOfSize:12];
    self.durationTimeLabel.text = @"00:00";
    [self.bottomView addSubview:self.durationTimeLabel];
    
    
    // 进度条
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(50, 2, Width - 105, 15)];
    [self.bottomView addSubview:self.progressSlider];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"slider_16_02"] forState:UIControlStateNormal];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"slider_16_02"] forState:UIControlStateHighlighted];
    // 最初的颜色
    self.progressSlider.maximumTrackTintColor = [UIColor whiteColor];
    // 划过之后的颜色
    self.progressSlider.minimumTrackTintColor = [UIColor purpleColor];
    
    // 添加响应事件
    [self.progressSlider addTarget:self action:@selector(sliderChange) forControlEvents:UIControlEventValueChanged];
}
#pragma mark 进度条滑动的响应事件
- (void)sliderChange{
    // 暂停播放器
    [self playerPause];
    // 获取当前时间
    double currentTime = self.durationTime * self.progressSlider.value;
    // 设置将要跳转的时间
    CMTime drage = CMTimeMake(currentTime, 1);
    // 对player进行设置
    [self.player seekToTime:drage completionHandler:^(BOOL finished) {
        // 启动播放器
        [self playerPlay];
        // 隐藏播放按钮
        [self.playButtonImageView setHidden:YES];
    }];
}

#pragma mark 创建视频结束的时候显示的视图
- (void)createPlayEndView{
    // 创建结束的时候显示的视图
    self.playEndView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, Width - 10, Height - 10)];
    self.playEndView.backgroundColor = [UIColor grayColor];
    self.playEndView.alpha = 0.8;
    
    [self addSubview:self.playEndView];
    
    // 显示视频结束后显示的图片
    UIImageView *endImageView = [[UIImageView alloc] initWithFrame:self.playEndView.frame];

    [self.playEndView addSubview:endImageView];
    
    // 创建显示重新播放的按钮
    UIButton *rePlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rePlayButton.frame = CGRectMake(0, 0, 100, 100);
    rePlayButton.center = CGPointMake(Width / 2, Height / 2);
    [rePlayButton addTarget:self action:@selector(rePlayVideo) forControlEvents:UIControlEventTouchUpInside];
    [rePlayButton setImage:[UIImage imageNamed:@"PlayIcon_64_01"] forState:UIControlStateNormal];
    rePlayButton.backgroundColor = [UIColor clearColor];
    [self.playEndView addSubview:rePlayButton];
    
    
    self.playEndView.hidden = YES;
}


// 重新播放视频
- (void)rePlayVideo{
    // 设置Player的播放时间是0
    [self.player seekToTime:CMTimeMake(0, 1) completionHandler:^(BOOL finished) {
        // 启动播放器
        [self playerPlay];
        // 隐藏播放按钮
        [self.playButtonImageView setHidden:YES];
        // 隐藏最后的视图
        self.playEndView.hidden = YES;
    }];
    
    
    
}

#pragma mark 轻点播放视图
- (void)tapPlayerView:(UIGestureRecognizer *)tap{
    if(self.isTap == NO){
        // 暂停视频
        [self playerPause];
        // 显示播放按钮
        [self.playButtonImageView setHidden:NO];
        // 隐藏加载按钮
        [self stopIndicator];
        
        // 如果读取到了视频的数据,就显示下面的滑动条
        if(self.isPlay != 0){
            [UIView animateWithDuration:1 animations:^{
                
                self.bottomView.alpha = 0.8;
            }];
        }
        self.isTap = YES;
    }
    else{
        // 启动播放视频
        [self playerPlay];
        // 隐藏播放按钮
        [self.playButtonImageView setHidden:YES];
        // 如果还没有读取到视频的数据,启动加载按钮
        if(self.isPlay == 0){
            [self showIndicator];
        }
        // 延时1秒钟后,隐藏下面的滑动条
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [UIView animateWithDuration:2 animations:^{
                
                self.bottomView.alpha = 0;
            }];
            self.isTap = NO;
        });
        
    }
    // 下面这样写,不安全
//    self.isTap = !self.isTap;
}
#pragma mark 添加监听方式,播放开始,播放结束,屏幕旋转
- (void)addNotificationCenters{
    // 初始化当前视频是否开始播放0表示第一次开始播放
    self.isPlay = 0;
    
    // 显示加载动画
    [self showIndicator];
    
    // 监听播放开始
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieStart:) name:AVPlayerItemTimeJumpedNotification object:nil];
    
    // 监听播放结束
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
// 移除监听
- (void)removeNotificationCenters{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 视频开始播放的时候触发的方法
- (void)movieStart:(NSNotification *)notification{
    // 0 的时候表示当前视频第一次开始播放
    if(self.isPlay == 0){
        // 停止加载动画
        [self stopIndicator];
    }
    // 改变判断量的值
    self.isPlay ++;
}
// 视频播放结束的时候触发的方法
- (void)movieEnd:(NSNotification *)notification{
    NSLog(@"视频播放完毕!");
    [self.playEndView setHidden:NO];
}
#pragma mark 设置播放进度
- (void)addPlayProgress{
    
    // 设置为每一秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 50) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        // 视频的总时间
        CGFloat durationTime = CMTimeGetSeconds(self.playerItem.duration);
        
        // 当前时间
        CGFloat currentTime = CMTimeGetSeconds(self.playerItem.currentTime);
        // 给Label赋值
        self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)currentTime / 60,(int)currentTime % 60];
        self.durationTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)durationTime / 60, (int)durationTime % 60];
        // 移动Slider
        self.progressSlider.value = currentTime / durationTime;
        
        // 保存总时长,用在手动快进的时候
        self.durationTime = durationTime;
        
    }];
}


#pragma mark 启动播放器
- (void)playerPlay{
    if(self.player != nil){
        [self.player play];
    }
    else{
        NSLog(@"播放器为空,不能启动!");
    }
}

#pragma mark 暂停播放器
- (void)playerPause{
    if(self.player != nil){
        [self.player pause];
    }
    else{
        NSLog(@"播放器为空,不能暂停!");
    }
}

#pragma mark 加载动画
// 显示加载动画
- (void)showIndicator{
    if(self.indicator == nil){
        self.indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        self.indicator.backgroundColor = [UIColor clearColor];
        self.indicator.center = CGPointMake(Width / 2, Height / 2);
        // 加载动画的样式
        self.indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        [self addSubview:self.indicator];
    }
    [self.indicator startAnimating];
}

// 停止加载动画
- (void)stopIndicator{
    [self.indicator stopAnimating];
}


@end
